<?php
/*********************** Easy-D ****************************
 @ 文件名称：Request.class.php
 @ 文件名称：请求处理类                   
 @ 文件作用：对路由分析的接口进行请求处理，会寻找相应的义务处理文件
 @ 维护人员：weixuan                                      
 ***********************************************************/

namespace coreLib\RequestClass;
use coreLib\ErrorClass\Error;
use coreLib\ResponseClass\Response;
use coreLib\CacheClass\Cache;

class Request{

	/*
	 * 构造函数
	 * @params {$route} 路由操作对象
	 * @params {$permissionm}	权限操作对象
	 * @params {$db}	数据库操作对象
	 * @params {$cache}	缓存操作对象
	 * @return 没有返回值
	 */
	function __construct($route,$db){

		//构建缓存对象
		$cache = new Cache($route);

		//构建响应处理对象
		$response = new Response($route,$cache);
	
		//请求接口必传参数验证
		$this->requestParamsValidation($route,$response);

		//判断是否有缓存，获取接口的缓存数据
		$cacheResult = $cache->getCacheData();

		//判断缓存是否获取成功
		if($cacheResult){

			//返回缓存结果
			$response->responseData( true, $cacheResult, true);

		}

		//所有接口进入前的入口文件
		if(file_exists(BASE_PATH."/business/initializtion.php")){
		   require_once(BASE_PATH."/business/initializtion.php");
		}

		//是否自动构建CURD
		if($route->isCURD){

			$paramsV = $GLOBALS['interfaceData'][$route->requestInterface];

			$autoTabel = $paramsV['autoTable'];
			$autoType  = $paramsV['autoType'];

			//判断构建类型
			if($autoType == 'C'){

				//新增
				$rsData = $db->mysqlDB->automaticAdd($route->bodyParams)->insert($autoTabel);

			}else if($autoType == 'U'){

				//更新
				$rsData = $db->mysqlDB->automaticUpdate($route->bodyParams)->update($autoTabel);

			}else if($autoType == 'R'){

				//查询
				$rsData = $db->mysqlDB->field($route->bodyParams)->params($route->restfulParams)->select($autoTabel);

			}else if($autoType == 'D'){

				//删除
				$rsData = $db->mysqlDB->automaticDelete($route->bodyParams)->delete($autoTabel);

			}else{

				Error::Result("REQUEST_ERROR",$GLOBALS['errorMsg']['autoCURDParamsError']);

			}

			$response->responseData( true , $rsData );

		}else{
			
			//当前业务接口进入前的入口文件
			if(file_exists(dirname($route->reuqestFilePath)."/initializtion.php")){
			   require_once(dirname($route->reuqestFilePath)."/initializtion.php");
			}

			//调用接口文件
			require_once($route->reuqestFilePath);

		}

	}

	/*
	 * 参数必传项验证
	 * @params {$route} 路由操作对象
	 * @params {$response} 返回结果操作对象
	 * @return 没有返回值
	 */
	protected function requestParamsValidation($route,$response){
		

		$paramsValidation = $GLOBALS['interfaceData'][$route->requestInterface];

	
		//判断是否需要验证		
		if(@$paramsValidation['getMustParams']!=NULL || @$paramsValidation['postMustParams']!=NULL){

		   //取出restful必填字段和验证条件
		   $restfulFieldArr     = array();
		   $restfulConditionArr = array();	
		   for($i=0;$i<count(@$paramsValidation['getMustParams']);$i++){
		   	   $tempArr = explode("|",$paramsValidation['getMustParams'][$i]);
		   	   array_push($restfulFieldArr,trim($tempArr[0]));
		   	   array_push($restfulConditionArr,trim($tempArr[1]));
		   }

		   //取出body必填字段和验证条件
		   $bodyFieldArr     = array();
		   $bodyConditionArr = array();	

		   for($i=0;$i<count(@$paramsValidation['postMustParams']);$i++){
		   	   $tempArr = explode("|",$paramsValidation['postMustParams'][$i]);
		   	   array_push($bodyFieldArr,trim($tempArr[0]));
		   	   array_push($bodyConditionArr,trim($tempArr[1]));
		   }

		 
		   $restfulValidation = $restfulFieldArr;
		   $bodyValidation    = $bodyFieldArr;
           
           //验证RESTFUL必填参数是否存在
           if($restfulValidation!=NULL){

           	  //取出当前传递的参数	
           	  $restfulKeyArr = $route->restfulParams==NULL?[]:array_keys($route->restfulParams);

           	  //获取未传递的restful参数
           	  $noRestFulParams = array_diff($restfulValidation,$restfulKeyArr);

           	  //如果有未填写的项，返回错误提示
			  if(count($noRestFulParams)>0){

                 //验证结果提示
			  	 $validationRestFulMessage = implode(",",$noRestFulParams);

			  	 //返回验证结果
			  	 $response->responseData(false,$GLOBALS['errorMsg']['restfulParamsError']['message'].":".$validationRestFulMessage);
			  
			  }

           }

           //restful必填参数进行格式验证
           for($i=0;$i<count($restfulFieldArr);$i++){

           		//取出正则验证规则
           		$pattern = $GLOBALS['regexpSettings'][$restfulConditionArr[$i]];
			    $restfulParamsValue = $route->restfulParams[$restfulFieldArr[$i]];
			
           		if($pattern){
           		    if($pattern == 'NOEMPTY'){
           		        if( empty($restfulParamsValue) )
           		        {
           		            $response->responseData(false,"参数:".$restfulFieldArr[$i]."不能为空");
           		        }
           		    }else{
           		        if(!preg_match($pattern, $restfulParamsValue)){
           		            $response->responseData(false,"参数:".$restfulFieldArr[$i]."格式不正确");
           		        }
           		    }
           		}else{
           		    $response->responseData(false,$GLOBALS['errorMsg']['noRegexpError']);
           		}
		   }	

		   
		   //验证BODY必填参数是否存在
           if($bodyValidation!=NULL){


           	  //取出当前存在的body参数
				 $bodyKeyArr = $route->bodyParams==NULL?[]:array_keys($route->bodyParams);
				 
           	  //获取未传递的body参数
				 $noBodyParams = array_diff($bodyValidation,$bodyKeyArr);
				 
				 
			  if(count($noBodyParams)>0){

                 //验证结果提示
			  	 $validationBodyMessage = implode(",",$noBodyParams);

			  	 //返回验证结果
			  	 $response->responseData(false,$GLOBALS['errorMsg']['bodyParamsError']['message'].":".$validationBodyMessage);
			  
			  }
		   }
		   
		   

           //body必填参数进行格式验证
           for($i=0;$i<count($bodyFieldArr);$i++){

           		//取出正则验证规则
           		$pattern 			= $GLOBALS['regexpSettings'][$bodyConditionArr[$i]];
				$bodyParamsValue    = $route->bodyParams[$bodyFieldArr[$i]];
				   
			
           		if($pattern){
           			if($pattern == 'NOEMPTY'){
           			    if( empty($bodyParamsValue)){
           			        $response->responseData(false,"参数:".$bodyFieldArr[$i]."不能为空");
           			    }
           			}else{
				
           				if(!preg_match($pattern, $bodyParamsValue)){
							$response->responseData(false,"参数:".$bodyFieldArr[$i]."格式不正确");
						}
           			}
           		}else{
           			$response->responseData(false,$GLOBALS['errorMsg']['noRegexpError']);
           		}
           }

		}
	} 
}
